package suray.rgv.communication;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.rgv.util.RgvLogger;
import com.suray.socket.SocketInterface;
import suray.rgv.communication.util.SeerMessageType;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * 两栖车交互
 */
public class Rgv60Comm {
    private SocketInterface socket;

    public Rgv60Comm(SocketInterface socket) {
        this.socket = socket;
    }

    public synchronized String comm(String des, SeerSendMessage message, int resendCount) throws IOException {
        try {
            socket.sendData(message.makeMessage());
            byte[] recData = socket.recData(2000);
            while (!checkData(recData)) {
                try {
                    byte[] resData = socket.recData(1000);
                    byte[] tempData = new byte[recData.length + resData.length];
                    System.arraycopy(recData, 0, tempData, 0, recData.length);
                    System.arraycopy(resData, 0, tempData, recData.length, resData.length);
                    recData = tempData;
                } catch (IOException e) {
                    RgvLogger.error(LoggerType.ERROR, null, null,
                            des + "接收到的数据不完整，通讯异常" +
                                    WcsFuncUtil.changeData(Arrays.copyOfRange(recData, 16, recData.length)),
                            this.getClass());
                    throw e;
                }
            }
            int sendType = message.getValue("type");
            int recType = WcsFuncUtil.combineToWord(recData[9], recData[8]);
            SeerMessageType sendMessageType = SeerMessageType.parseSendType(sendType);
            if (sendMessageType.getReceiveValue() != recType) {
                return comm(des, message, resendCount);
            } else {
                String result = WcsFuncUtil.changeData(Arrays.copyOfRange(recData, 16, recData.length));
                RgvLogger.debug(LoggerType.COMM_DATA, null, des, " 返回数据:" + result, SeerCommManage.class);
                return result;
            }
        } catch (IOException e) {
            if (resendCount > 0) {
                WcsFuncUtil.delay(1000);
                return comm(des, message, --resendCount);
            } else {
                throw e;
            }
        }
    }

    private boolean checkData(byte[] recData) {
        int leftNum = 0, rightNum = 0;

        for (int i = 16; i < recData.length; i++) {
            if (recData[i] == '{') {
                leftNum++;
            } else if (recData[i] == '}') {
                rightNum++;
            }
        }

        if (leftNum == rightNum) {
            return true;
        }

        return false;
    }

    public boolean isOnline() {
        return socket.isOnline();
    }

    public void close() {
        SocketInterface.deleteSocket(socket);
    }
}
